<div class="m-bg">
<h1>SQL GROUP BY 语句</h1>
<p class="intro">Aggregate 函数常常需要添加 GROUP BY 语句。</p> <h2>GROUP BY 语句</h2> <p>GROUP BY 语句用于结合 Aggregate 函数，根据一个或多个列对结果集进行分组。</p> <h3>SQL GROUP BY 语法</h3> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT column_name, aggregate_function(column_name)<br/> FROM table_name<br/> WHERE column_name operator value<br/> GROUP BY column_name; </div></code></pre></div> <h2>演示数据库</h2> <p>在本教程中，我们将使用众所周知的 Northwind 样本数据库。</p> <p>下面是选自 "Orders" 表的数据：</p> <table class="reference notranslate">
<tr>
<th>OrderID</th> <th>CustomerID</th> <th>EmployeeID</th> <th>OrderDate</th> <th>ShipperID</th> </tr>
<tr>
<td>10248</td> <td>90</td> <td>5</td> <td>1996-07-04</td> <td>3</td> </tr>
<tr>
<td>10249</td> <td>81</td> <td>6</td> <td>1996-07-05</td> <td>1</td> </tr>
<tr>
<td>10250</td> <td>34</td> <td>4</td> <td>1996-07-08</td> <td>2</td> </tr>
</table>
<p>选自 "Shippers" 表的数据：</p> <table class="reference notranslate">
<tr>
<th>ShipperID</th> <th>ShipperName</th> <th>Phone</th> </tr>
<tr>
<td>1</td> <td>Speedy Express</td> <td>(503) 555-9831</td> </tr>
<tr>
<td>2</td> <td>United Package</td> <td>(503) 555-3199</td> </tr>
<tr>
<td>3</td> <td>Federal Shipping</td> <td>(503) 555-9931</td> </tr>
</table>
<p>选自 "Employees" 表的数据：</p> <table class="reference notranslate">
<tr>
<th>EmployeeID</th> <th>LastName</th> <th>FirstName</th> <th>BirthDate</th> <th>Photo</th> <th>Notes</th> </tr>
<tr>
<td>1</td> <td>Davolio</td> <td>Nancy</td> <td>1968-12-08</td> <td>EmpID1.pic</td> <td>Education includes a BA....</td> </tr>
<tr>
<td>2</td> <td>Fuller</td> <td>Andrew</td> <td>1952-02-19</td> <td>EmpID2.pic</td> <td>Andrew received his BTS....</td> </tr>
<tr>
<td>3</td> <td>Leverling</td> <td>Janet</td> <td>1963-08-30</td> <td>EmpID3.pic</td> <td>Janet has a BS degree....</td> </tr>
</table>
<h2>SQL GROUP BY 实例</h2> <p>现在我们想要查找每个送货员配送的订单数目。</p> <p>下面的 SQL 语句按送货员进行订单分类统计：</p> <div class="example margin-b-10"> <h2 class="example">实例</h2> <pre><code class="language-sql"><div class="example_code notranslate"> SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders<br/>LEFT JOIN Shippers<br/>ON Orders.ShipperID=Shippers.ShipperID<br/> GROUP BY ShipperName; </div></code></pre> </div> <h2>GROUP BY 一个以上的列</h2> <p>我们也可以对一个以上的列应用 GROUP BY 语句，如下所示：</p> <div class="example margin-b-10"> <h2 class="example">实例</h2> <pre><code class="language-sql"><div class="example_code notranslate"> SELECT Shippers.ShipperName, Employees.LastName,<br/> COUNT(Orders.OrderID) AS NumberOfOrders<br/> FROM ((Orders<br/>INNER JOIN Shippers<br/>ON Orders.ShipperID=Shippers.ShipperID)<br/>INNER JOIN Employees<br/>ON Orders.EmployeeID=Employees.EmployeeID)<br/>GROUP BY ShipperName,LastName; </div></code></pre> </div> <div class="text-center padding-10 margin-t-5">
</div>
</div>